package com.walter.quickstart;

import com.walter.quickstart.dao.PersonRespository;
import com.walter.quickstart.domain.Person;
import io.quarkus.hibernate.orm.panache.PanacheQuery;
import io.quarkus.panache.common.Page;

import javax.inject.Inject;
import javax.transaction.Transactional;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Path("/person")
@Transactional
public class PersonResource {

    @Inject
    PersonRespository personRespository;

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public Response addPerson(Person person){
        person.persist();
        return Response.ok().build();
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<Person> getPersons(){
        List<Person> l = Person.listAll();
        return l;
    }

    @GET
    @Path("/getByPNum")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.TEXT_PLAIN)
    public List<Person> getByPNum(@QueryParam("phone_number") String phone_number){
        return Person.getByPNum(phone_number);
    }

    //按Id查询
    @GET
    @Path("/byId/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.TEXT_PLAIN)
    public Person getById(@PathParam("id") Long id){
        return Person.getById(id);
    }

    //统计条数
    @GET
    @Path("/count")
    @Produces(MediaType.TEXT_PLAIN)
    @Consumes(MediaType.TEXT_PLAIN)
    public long count(){
        Map<String,Object> map = new HashMap<>();
        map.put("id", 1L);
        map.put("phone_number", "1363185xxx");
        return Person.count(" id = :id and phone_number = :phone_number ", map);
        //return Person.count();
    }
    //分页
    @GET
    @Path("/page")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.TEXT_PLAIN)
    public List<Person> page(){
        PanacheQuery<Person> persons = Person.findAll();
        return persons.page(Page.of(3,5)).list();//从第3页开始，取10条
    }

    //分页
    @GET
    @Path("/page/{page}")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.TEXT_PLAIN)
    public List<Person> page2(@PathParam("page") int page){
        PanacheQuery<Person> persons = Person.findAll().page(Page.of(page,5)).nextPage();
        return persons.list();
    }

}
